package com.recharge.srevice;

import java.lang.reflect.InvocationTargetException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.entity.ChildMeter;
import com.entity.Customer;
import com.entity.CustomerMeter;
import com.entity.CustomerMeterPK;
import com.entity.Recharge;
import com.file.entity.FileCustomer;
import com.file.service.CustomerService;
import com.interfaces.ChildMeterDao;
import com.interfaces.CustomerDao;
import com.interfaces.CustomerMeterDao;
import com.interfaces.MeterDao;
import com.interfaces.RechargeDao;
import com.interfaces.SysdicDao;
import com.recharge.entity.JsonRecharge;
import com.recharge.entity.JsonRechargeCustomer;
import com.setting.service.SysdicService;
import com.utils.CglibBeanCopierUtils;
import com.utils.JsonResult;
import com.utils.Utils;

/**
 * @Title: RechargeService.java
 * @Package com.recharge.srevice
 * @author 孙梦楠
 * @date 2017年8月23日 下午4:32:29
 * @version V1.0.0
 */
@Service
public class RechargeService {

	private static final Logger log = LoggerFactory.getLogger(RechargeService.class);

	@Autowired
	private RechargeDao rechargedao;

	@Autowired
	private CustomerDao customerdao;

	@Autowired
	private CustomerService customerservice;

	@Autowired
	private SysdicDao sysdicdao;

	@Autowired
	private CustomerMeterDao customermeterdao;

	@Autowired
	private MeterDao meterdao;

	@Autowired
	private SysdicService sysdicservice;

	@Autowired
	private ChildMeterDao childmeterdao;

	// 列出可充值用户列表
	@Transactional
	public JsonResult<List<JsonRechargeCustomer>> list_recharge_customer(String opeorgcookie, String opetypecookie,
			String customeraccount, String customername, String customeraddress, String languagecookie,
			String childtotalstatus) {

		List<Customer> customers = new ArrayList<Customer>();

		customers = customerdao.findByConditions_recharge(customeraccount, customername, customeraddress,
				Integer.valueOf(opeorgcookie), opetypecookie, "2", "2");
		List<JsonRechargeCustomer> jsonRechargeCustomers = new ArrayList<JsonRechargeCustomer>();

		for (int i = 0; i < customers.size(); i++) {

			JsonRechargeCustomer jsonRechargeCustomer = new JsonRechargeCustomer();
			Customer customer = customers.get(i);
			Integer customerid = customers.get(i).getCustomerid();
			jsonRechargeCustomer.setCustomerid(customerid);
			jsonRechargeCustomer.setCustomeraccount(customer.getCustomeraccount());
			jsonRechargeCustomer.setCustomername(customer.getCustomername());
			jsonRechargeCustomer.setCustomeraddress(customer.getCustomeraddress());
			jsonRechargeCustomer.setCustomerorg(customer.getCustomerorg());
			jsonRechargeCustomer.setCustomertype(customer.getCustomertype());
			jsonRechargeCustomer.setCustomerorgname(
					sysdicservice.finddisplay("0001", customer.getCustomerorg().toString(), languagecookie));
			if (rechargedao.findByCustomeridAndDirectionAndFrequencyNotOrderByFrequencyDesc(customerid, "购电", 0)
					.size() == 0) {
				jsonRechargeCustomer.setFrequency(0);
			} else {
				// 查找最新一条
				Recharge recharge = rechargedao
						.findByCustomeridAndDirectionAndFrequencyNotOrderByFrequencyDesc(customerid, "购电", 0).get(0);
				// 购电次数
				jsonRechargeCustomer.setFrequency(recharge.getFrequency());
			}
			// 剩余金额 通过用户ID查表ID 通过表ID查剩余金额
			Integer meterid = customermeterdao.findByCustomerid2(customerid).getPk().getMeterid();

			Double beforemoney = meterdao.findOne(meterid).getMetermoney();
			jsonRechargeCustomer.setMeterid(meterid);
			jsonRechargeCustomer.setBeforemoney(beforemoney);
			// 总分关系
			ChildMeter cm = childmeterdao.findByMeterid(meterid);

			if (childtotalstatus.equals("总")) {
				// 如果已设置表而且是总表
				if (cm != null && cm.getFathermeterid() == 0) {
					jsonRechargeCustomers.add(jsonRechargeCustomer);
				}
			} else {
				// 如果是未设置表或者是分表
				if (cm == null// 未设置表
						|| (cm != null && cm.getFathermeterid() == null)// 设置分表但是未关联总表
						|| (cm != null && cm.getFathermeterid() != 0)// 关联过的分表
				) {
					jsonRechargeCustomers.add(jsonRechargeCustomer);
				}
			}

		}

		return new JsonResult<List<JsonRechargeCustomer>>(511, "列出已开户用户", jsonRechargeCustomers);
	}

	// 充值
	@Transactional
	public JsonResult<Recharge> recharge(Integer customerid, String opecodecookie, Double money) {

		if (money == null) {
			return new JsonResult<Recharge>(512, "充值失败..金额错误", null);

		} else {

			Recharge recharge = new Recharge();
			recharge.setCustomerid(customerid);
			Customer customer = customerdao.findOne(customerid);
			Integer meterid = customermeterdao.findByCustomerid2(customerid).getPk().getMeterid();
			recharge.setMeterid(meterid);
			recharge.setCustomeraccount(customer.getCustomeraccount());
			recharge.setCustomername(customer.getCustomername());
			recharge.setCustomeraddress(customer.getCustomeraddress());
			recharge.setCustomerorg(customer.getCustomerorg());
			recharge.setCustomertype(customer.getCustomertype());
			recharge.setDirection("购电");
			recharge.setOpecode(opecodecookie);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String issuetime = sdf.format(new Date());
			recharge.setIssuetime(issuetime);
			if (rechargedao.findByCustomeridAndDirectionAndFrequencyNotOrderByFrequencyDesc(customerid, "购电", 0)
					.size() == 0) {
				recharge.setFrequency(1);

			} else {
				Integer frequency = rechargedao
						.findByCustomeridAndDirectionAndFrequencyNotOrderByFrequencyDesc(customerid, "购电", 0).get(0)
						.getFrequency();
				frequency++;
				recharge.setFrequency(frequency);
			}
			/*
			 * beforemoney 调用接口 aftermoney 接口
			 */

			recharge.setMoney(money);
			// Double totalmoney = rechargedao
			// .findByCustomeridAndDirectionAndFrequencyNotOrderByFrequencyDesc(customerid,
			// "购电", 0).get(0)
			// .getTotalmoney();
			// recharge.setTotalmoney(totalmoney);

			recharge.setOptstatus("等待下发");
			recharge.setOptnum(0);

			rechargedao.save(recharge);
			return new JsonResult<Recharge>(512, "充值命令已下发", recharge);
		}
	}

	// 充值历史记录
	@Transactional
	public JsonResult<List<JsonRecharge>> rechargehistory(Integer customerid, String languagecookie) {

		List<Recharge> recharges = rechargedao
				.findByCustomeridAndDirectionAndFrequencyNotOrderByFrequencyDesc(customerid, "购电", 0);
		List<JsonRecharge> rechargehistories = list_history(recharges, languagecookie);

		return new JsonResult<List<JsonRecharge>>(514, "充值历史记录", rechargehistories);
	}

	// 组装前端类
	public List<JsonRecharge> list_history(List<Recharge> recharges, String languagecookie) {
		List<JsonRecharge> rechargehistories = new ArrayList<JsonRecharge>();

		for (Recharge recharge : recharges) {
			JsonRecharge jsonRecharge = new JsonRecharge();
			CglibBeanCopierUtils.copyProperties(recharge, jsonRecharge);
			String customertypename = sysdicservice.finddisplay("0006", recharge.getCustomertype(), languagecookie);
			jsonRecharge.setCustomertype(customertypename);
			rechargehistories.add(jsonRecharge);
		}

		return rechargehistories;
	}

	// 工单状态：0 等待下发, 1 下发成功，2 下发失败，3 正在下发
	@Transactional
	public List<Recharge> findByOptstatus(Integer status) {

		String optstatus = doOptstatus(status);

		List<Recharge> recharges = rechargedao.findByOptstatusOrderByRechargeid(optstatus);

		return recharges;
	}

	// 查找状态为“等待下发”和“正在下发”的每个表的第一条。
	@Transactional
	public List<Recharge> findByOptstatusGroupByMeterid() {

		List<Recharge> recharges = rechargedao.findByOptstatusGroupByMeterid();

		return recharges;
	}

	// private List<Recharge> changeMoney(List<Recharge> recharges) {
	// List<Recharge> recharges2 = new ArrayList<>();
	// for (Recharge recharge : recharges) {
	// Recharge recharge2 = new Recharge();
	// DecimalFormat df = new DecimalFormat("#.00");
	// recharge2.setRechargeid(recharge.getRechargeid());
	// recharge2.setMeterid(recharge.getMeterid());
	// recharge2.setCustomerid(recharge.getCustomerid());
	// recharge2.setCustomeraccount(recharge.getCustomeraccount());
	// recharge2.setCustomername(recharge.getCustomername());
	// recharge2.setCustomerorg(recharge.getCustomerorg());
	// recharge2.setCustomertype(recharge.getCustomertype());
	// recharge2.setDirection(recharge.getDirection());
	// recharge2.setOpecode(recharge.getOpecode());
	// recharge2.setIssuetime(recharge.getIssuetime());
	// recharge2.setRechargetime(recharge.getRechargetime());
	// recharge2.setBeforemoney(Double.valueOf(df.format(recharge.getBeforemoney())));
	// recharge2.setFrequency(recharge.getFrequency());
	// recharge2.setMoney(Double.valueOf(df.format(recharge.getMoney())));
	// recharge2.setAftermoney(Double.valueOf(df.format(recharge.getAftermoney())));
	// recharge2.setTotalmoney(Double.valueOf(df.format(recharge.getTotalmoney())));
	// recharge2.setOptstatus(recharge.getOptstatus());
	// recharge2.setOptnum(recharge.getOptnum());
	// recharge2.setPrintnum(recharge.getPrintnum());
	// recharge2.setRemark(recharge.getRemark());
	// recharge2.setAppno(recharge.getAppno());
	// recharge2.setChargetime(recharge.getChargetime());
	// recharge2.setBankno(recharge.getBankno());
	// recharge2.setBankname(recharge.getBankname());
	// recharge2.setBankaccount(recharge.getBankaccount());
	// recharge2.setIssuetime(recharge.getIssuetime());
	// recharge2.setRealmoney(Double.valueOf(df.format(recharge.getRealmoney())));
	// recharge2.setArrearage(Double.valueOf(df.format(recharge.getArrearage())));
	// }
	// return recharges2;
	// }
	// 表端更新数据
	@Transactional
	public boolean updateRecharge(List<Recharge> list) {

		for (Recharge recharge : list) {
			Integer rechargeid = recharge.getRechargeid();
			String rechargetime = recharge.getRechargetime();
			Double beforemoney = recharge.getBeforemoney();
			Double aftermoney = recharge.getAftermoney();
			Double totalmoney = recharge.getTotalmoney();
			String status = recharge.getOptstatus();
			String optstatus = doOptstatus(Integer.valueOf(status));
			Integer optnum = recharge.getOptnum();
			String remark = recharge.getRemark();
			rechargedao.updateRecharge(rechargetime, beforemoney, aftermoney, totalmoney, optstatus, optnum, remark,
					rechargeid);
		}

		return true;
	}

	public String doOptstatus(Integer status) {
		String optstatus = null;
		switch (status) {
		case 0:
			optstatus = "等待下发";
			break;
		case 1:
			optstatus = "下发成功";
			break;
		case 2:
			optstatus = "下发失败";
			break;
		case 3:
			optstatus = "正在下发";
			break;
		default:
			optstatus = null;
			break;
		}
		return optstatus;
	}

}
